package org.kth.dks.dks_comm;

import java.net.MalformedURLException;
import java.util.regex.Pattern;

public class DKSNetAddress {
  private int port = 0;
  private String ip = null;
  private static final Pattern dksUrl =
      Pattern.compile("^dksnet://(.*?):(\\d*.?)$", Pattern.CASE_INSENSITIVE);

  /**
   * Constructs a DKSNetAddress from a DKSNETURL string having the following format:
   * <b>dksnet://[IP]:[PORT]</b><br>
   * IP can be either an IP number of a hostname,
   * PORT must be an integer (<=65535) describing the port number of the DKS,
   * The scheme of the url can be in any case, e.g. "dksnet://" or "DKSNet://".<br><br>
   * Example DKSNETURL <i>"dksnet://localhost:8080"</i>
   * @param dksURL String with the above described format
   * @throws MalformedURLException if the string does not match the above description
   */
  public DKSNetAddress( String dksURL ) throws MalformedURLException
  {
    if (!dksUrl.matcher(dksURL).matches()) {
      throw new MalformedURLException("Only DKS scheme supported (dksnet://<IP>:<PORT>)");
    }

    String colons = dksUrl.matcher(dksURL).replaceAll("$1:$2");
    String [] sp = colons.split(":");

    ip   = sp[0];
    port = Integer.parseInt(sp[1]);
  }

  public DKSNetAddress(String newip, int newport) {
    port = newport;
    ip = newip;
  }

  /**
   * Returns the DKSNetURL representing this DKSNetNetwork in the following format:
   * <b>dksnet://[IP]:[PORT]</b><br>
   * IP can be either an IP number of a hostname,
   * PORT must be an integer (<=65535) describing the port number of the DKS,
   * The scheme of the url can be in any case, e.g. "dksnet://" or "DKSNet://".<br><br>
   * Example DKSNETURL <i>"dksnet://localhost:8080"</i>
   * @return String the DKSNETURL representing this object
   */
  public String getDKSNetURL() {
    return "DKSNet://"+ip+":"+port;
  }

  public String toString() { return getDKSNetURL(); }

  public int getPort() {
    return port;
  }

  public String getIP() {
    return ip;
  }

  public boolean equals(Object o) {
    if (o==this)
      return true;
    else if (!(o instanceof DKSNetAddress))
      return false;
    else {
      DKSNetAddress addr = (DKSNetAddress) o;
      return port==addr.port && ip.equals(addr.ip);
    }
  }

  public int hashCode() {
    int tmp = 17;
    tmp = 37*tmp + port;
    tmp = 37*tmp + ip.hashCode();
    return tmp;
  }
}//DKSNetAddress class
